package com.riche.contractbackend.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.riche.contractbackend.model.domain.User;
import com.riche.contractbackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: PreCacheJob
 * @Description: 缓存预热定时任务
 * @Author: Gaoruiqi
 * @Date: 2025-09-08 20:45
 * @Version: 1.0
 **/

@Component
@Slf4j
public class PreCacheJob {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private UserService userService;

    @Resource
    private RedissonClient redissonClient;

    // 重点用户
    private List<Long> mainUserLists = Collections.singletonList(1L);

    /**
     * 定时任务，每天执行
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void doCacheRecommendUser() {
        log.info("开始缓存推荐用户");
        // todo 获取锁
        RLock lock = redissonClient.getLock("contract:PreCacheJob:doCacheRecommendUser:lock");
        try {
            // 只有一个线程可以获取锁
            if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                log.info("获取锁成功--------------------------" + Thread.currentThread().getId());
                for (Long userId : mainUserLists) {
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    queryWrapper.ne("id", userId);
                    Page<User> page = userService.page(new Page<>(1, 20), queryWrapper);
                    String redisKey = String.format("contract:user:recommend:%s", userId);
                    ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
                    // 写缓存
                    try {
                        valueOperations.set(redisKey, page, 30000, TimeUnit.MILLISECONDS);
                    } catch (Exception e) {
                        log.error("redis set key error", e);
                    }
                }
            }
        } catch (InterruptedException e) {
            log.error("doCacheRecommendUser error", e);
        } finally {
            // 是否只释放自己的锁
            if (lock.isHeldByCurrentThread()) {
                log.info("释放锁成功");
                lock.unlock();
            }
        }
    }
}
